<template>
  <div class="form_dialog">
    <!-- 发送日报弹框 -->
    <el-dialog
      v-model="visible"
      title="发送日报"
      :append-to-body="true"
      :show-close="false"
      :close-on-click-modal="false"
      :top="isPhone ? '0' : '10vh'"
      :width="isPhone ? '100%' : '800px'"
      center
    >
      <div v-loading="dialogLoading" class="dialog_container">
        <div class="report_cell_title">
          <span>上个工作日完成</span>
          <span v-if="lastFinishReportList.length" class="time_text">
            {{ lastFinishReportList[0].reportTime }}
          </span>
        </div>

        <div v-if="lastFinishReportList.length" class="report_cell_content">
          <div
            v-for="(item, i) in lastFinishReportList"
            :key="i"
            class="report_cell_item"
          >
            <span class="nowrap">{{ i + 1 }}、</span>
            <div class="f_1">
              <span v-for="(cell, j) in item.moduleNamesArr" :key="j">
                【{{ cell }}】
              </span>
              <span>{{ item.reportText }}</span>
            </div>
            <span v-if="Number(item.workProgress)" class="nowrap ml_s">
              {{ item.workProgress }}%
            </span>
            <div class="delete_btn" @click="deleteLastReportMethod(i)">
              <delete-filled
                style="
                  width: 1.2em;
                  height: 1.2em;
                  margin-right: 14px;
                  color: #f56c6c;
                "
              />
            </div>
          </div>
        </div>
        <div v-else style="color: #999; padding: 10px 20px">无</div>

        <div class="report_cell_title">
          <span>今日工作计划</span>
          <span v-if="todayPlanReportList.length" class="time_text">
            {{ todayPlanReportList[0].reportTime }}
          </span>
        </div>

        <div class="report_cell_content">
          <div
            v-for="(item, i) in todayPlanReportList"
            :key="i"
            class="report_cell_item"
          >
            <span class="nowrap">{{ i + 1 }}、</span>
            <div class="f_1">
              <span v-for="(cell, j) in item.moduleNamesArr" :key="j">
                【{{ cell }}】
              </span>
              <span>{{ item.reportText }}</span>
            </div>
            <span v-if="Number(item.workProgress)" class="nowrap ml_s">
              {{ item.workProgress }}%
            </span>
            <div class="delete_btn" @click="deleteTodayReportMethod(i)">
              <delete-filled
                style="
                  width: 1.2em;
                  height: 1.2em;
                  margin-right: 14px;
                  color: #f56c6c;
                "
              />
            </div>
          </div>
        </div>

        <div class="report_cell_title">上个工作日问题反馈</div>

        <div class="input_remark_box">
          <!-- .trim属性会使最下排文字不能换行 -->
          <el-input
            v-model="form.reportCommitRemark"
            placeholder="填写是否有项目延误、项目问题等情况..."
            type="textarea"
            rows="5"
            clearable
            maxlength="2000"
            show-word-limit
          ></el-input>
        </div>
      </div>
      <template #footer>
        <div class="dialog_footer">
          <el-button
            type="primary"
            @click="handleConfirm"
            :loading="confirmBtnLoading"
            size="small"
          >
            发送
          </el-button>
          <el-button @click="close" size="small">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, getCurrentInstance, computed } from "vue";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
import { cloneDeep } from "lodash";

const initFormData = () => {
  return {
    reportCommitRemark: null,
    lastFinishReportIds: null,
    todayPlanReportIds: null,
  };
};

export default {
  name: "ReportCommitDialog",
  setup(props, context) {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const store = useStore();
    // 弹框是否显示
    const visible = ref(false);
    // 是否开启整个弹框loading（开启时无法关闭弹框）
    const dialogLoading = ref(false);
    // 确认按钮loading（开启时可以关闭弹框）
    const confirmBtnLoading = ref(false);
    // 表单数据
    const form = reactive(initFormData());
    // 编辑还是新增
    const isEdit = ref(false);
    // 上个工作日完成的日报记录
    const lastFinishReportList = ref([]);
    // 今日计划工作的日报记录
    const todayPlanReportList = ref([]);

    // 保存
    const handleConfirm = () => {
      confirmBtnLoading.value = true;
      form.lastFinishReportIds = lastFinishReportList.value.map(
        (item) => item.id
      );
      form.todayPlanReportIds = todayPlanReportList.value.map(
        (item) => item.id
      );
      $api.reportCommit
        .sendTodayReport(form)
        .then((res) => {
          confirmBtnLoading.value = false;
          ElMessage.success("发送成功！");
          // 触发事件，把数据传递给父组件
          context.emit("refresh");
          close();
        })
        .catch((err) => {
          confirmBtnLoading.value = false;
          console.error("updateUsersGroup error: ", err);
        });
    };

    // 打开弹框
    const open = (list) => {
      if (list) {
        isEdit.value = true;
        todayPlanReportList.value = cloneDeep(list);
      } else {
        // 新增
        isEdit.value = false;
      }
      getLastFinishReportList();
      visible.value = true;
    };

    // 关闭弹框
    const close = () => {
      if (confirmBtnLoading.value || dialogLoading.value) {
        return;
      }
      resetData();
      visible.value = false;
    };

    // 重置数据
    const resetData = () => {
      // 重置表单数据
      Object.keys(form).forEach((item) => {
        form[item] = initFormData()[item];
      });
      lastFinishReportList.value = [];
      todayPlanReportList.value = [];
    };

    // 获取登录用户的上个工作日的日报列表
    const getLastFinishReportList = () => {
      dialogLoading.value = true;
      $api.report
        .lastWorkDayReportSelf()
        .then((res) => {
          lastFinishReportList.value = res.data.map((item) => {
            return {
              ...item,
              checked: false,
              moduleNamesArr: item.moduleNames
                .split("|")
                .filter((item) => item),
              moduleIdsArr: item.moduleIds.split("|").filter((item) => item),
            };
          });
        })
        .catch((err) => {
          console.error("lastWorkDayReportSelf error: ", err);
        })
        .finally(() => {
          dialogLoading.value = false;
        });
    };

    const deleteLastReportMethod = (index) => {
      lastFinishReportList.value.splice(index, 1);
    };

    const deleteTodayReportMethod = (index) => {
      if (todayPlanReportList.value.length <= 1) {
        return ElMessage.warning("今日工作计划至少为一条");
      }
      todayPlanReportList.value.splice(index, 1);
    };

    // 计算属性
    const userInfo = computed(() => store.state.user.userInfo);
    const isPhone = computed(() => store.state.isPhone);

    return {
      visible,
      dialogLoading,
      confirmBtnLoading,
      form,
      isPhone,
      open,
      close,
      handleConfirm,
      isEdit,
      userInfo,
      lastFinishReportList,
      todayPlanReportList,
      deleteLastReportMethod,
      deleteTodayReportMethod,
    };
  },
};
</script>

<style lang="less" scoped>
.dialog_container {
  // height: 350px;
  // display: flex;
  // flex-direction: column;
  .report_cell_title {
    font-size: 16px;
    padding: 10px 20px;
    // background-image: linear-gradient(to right top, #ec008c, #6739b6);
    background-color: #faecd8;
    color: #303133;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .time_text {
      font-size: 14px;
      font-weight: 400;
      color: #999;
    }
  }
  .report_cell_content {
    .report_cell_item {
      padding: 10px 20px;
      padding-right: 40px;
      display: flex;
      line-height: 20px;
      // border-bottom: 1px solid #ebeef5;
      position: relative;
      &:hover {
        background-color: #f2f2f2;
        .delete_btn {
          display: block;
        }
      }
      &:last-child {
        border: 0;
      }
    }
    .delete_btn {
      position: absolute;
      right: 0px;
      top: 50%;
      transform: translateY(-44%);
      display: none;
      cursor: pointer;
      z-index: 10;
    }
  }
  .input_remark_box {
    padding-top: 10px;
  }
}
.dialog_footer {
}
</style>
